package com.wu.project.admin.interceptor;

import com.wu.project.admin.annotations.Authorization;
import com.wu.project.admin.component.AuthorizedResultHandler;
import com.wu.project.admin.property.Constants;
import com.wu.project.admin.util.JwtUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Arrays;

/**
 * @author xuan
 */
@Component
public class AuthorizedInterceptor implements HandlerInterceptor {

    Logger logger = LoggerFactory.getLogger(AuthorizedInterceptor.class);

    @Autowired
    AuthorizedResultHandler authorizedResultHandler;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handlerObj) throws Exception {
        String requestURI = request.getRequestURI();
        if (requestURI.contains(Constants.STRING_SPLIT_END)) {
            return true;
        }

        if ("/".equals(requestURI)) {
            return true;
        }

        HandlerMethod handler;
        try {
            handler = (HandlerMethod) handlerObj;
        } catch (Exception e) {
            return true;
        }
        Authorization annotation = handler.getMethod().getAnnotation(Authorization.class);
        if (annotation != null && annotation.isAuth()) {
            String authorized = request.getHeader("Authorized");
            if (StringUtils.hasLength(authorized)) {
                boolean isAuth = JwtUtil.Instance.verifyToken(authorized);
                if (isAuth) {
                    return true;
                }
            }
            authorizedResultHandler.authErrorHandler(response);
            return false;
        } else {
            return true;
        }
    }

    private Boolean checkRole(String role, String annotationRole) {
        if (annotationRole.contains(Constants.STRING_SPLIT)) {
            String[] splits = annotationRole.split(Constants.STRING_SPLIT);
            return Arrays.asList(splits).contains(role);
        } else {
            return role.equals(annotationRole);
        }
    }

    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
    }
}
